package com.yuzhantao.collection.sensorflow.service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.concurrent.TimeUnit;

import org.jboss.logging.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.alibaba.fastjson.JSON;
import com.google.common.util.concurrent.AbstractScheduledService;
import com.yuzhantao.collection.mq.ActiveMqClient;
import com.yuzhantao.collection.sensorflow.message.PushTemperatureMessage;
import com.yuzhantao.collection.sensorflow.message.SensorManage;
import com.yuzhantao.collection.sensorflow.message.SensorParamesEntity;
import com.yuzhantao.collection.sensorflow.response.message.SensorOfAwsPostdataEntity;

/**
 * 定时推送温度服务
 * 
 * @author yuzhantao
 *
 */
@Service(value = "pushTemperatureService")
public class PushTemperatureService extends AbstractScheduledService {
	protected final static Logger logger = Logger.getLogger(PushTemperatureService.class);
	private static final String SEND_ACTION_CODE = "realTimeDatas";
	private static final String DEV_TYPE = "SensorFlow";
	private static final String SEND_TOPIC = "damRealTimeInfoToService";
	private static final long TEMPERATURE_TIMEOUT = 1000 * 60; // 更新温度的超时时间
	@Autowired
	protected ActiveMqClient activeMqClient;
	/**
	 * 初始化时的延时时间，我们
	 */
	protected long initialdelay = 30;
	/**
	 * 延时间隔时间
	 */
	protected long delay = 30;

	@Override
	protected void runOneIteration() throws Exception {
		try {
			// 遍历所有机柜的温度信息并上传
			Iterator<Entry<String, Map<Integer, SensorParamesEntity>>> iterator = SensorManage.getInstance().getMap()
					.entrySet().iterator();
			while (iterator.hasNext()) {
				Entry<String, Map<Integer, SensorParamesEntity>> entry = iterator.next();
				this.pushToMQ(entry.getKey(), entry.getValue());
			}
		} catch (Exception e) {
			logger.error(e);
		}
	}

	@Override
	protected Scheduler scheduler() {
		return Scheduler.newFixedRateSchedule(this.initialdelay, this.delay, TimeUnit.SECONDS);
	}

	/**
	 * 推送温度数据到MQ
	 * 
	 * @param deviceCode
	 * @param sensorMap
	 */
	protected void pushToMQ(String deviceCode, Map<Integer, SensorParamesEntity> sensorMap) {
		PushTemperatureMessage msg = new PushTemperatureMessage();
		msg.setActioncode(SEND_ACTION_CODE);

		// 将1到42U数据保存到1到3u的map数组里
		Map<Integer, List<Integer>> temperatureList = new HashMap<>();
		Iterator<Entry<Integer,SensorParamesEntity>> iterator = sensorMap.entrySet().iterator();
		while (iterator.hasNext()) {
			Entry<Integer,SensorParamesEntity> entry = iterator.next();
			SensorParamesEntity spe = entry.getValue();

			if (spe == null || System.currentTimeMillis() - spe.getUpateTime() > TEMPERATURE_TIMEOUT) {
				iterator.remove();
				continue;
			} else {
				int uPos = spe.getSensorPosition() / 14 + 1;
				if (temperatureList.containsKey(uPos) == false) {
					temperatureList.put(uPos, new ArrayList<Integer>());
				}
				temperatureList.get(uPos).add(Double.valueOf(String.valueOf(spe.getSensorDatas())).intValue());
			}
		}

		// 将1到3u的温度数据，在每u里求平均值存放到sensorList数组
		List<SensorParamesEntity> sensorList = new ArrayList<>();
		Iterator<Entry<Integer, List<Integer>>> ite = temperatureList.entrySet().iterator();
		while (ite.hasNext()) {
			Entry<Integer, List<Integer>> entry = ite.next();
			if (entry == null || entry.getValue().size() == 0)
				continue;
			SensorParamesEntity spe = new SensorParamesEntity();
			spe.setSensorType(1);
			spe.setSensorPosition(entry.getKey());
			long temp = 0;
			for (int i = 0; i < entry.getValue().size(); i++) {
				temp += entry.getValue().get(i);
			}
			spe.setSensorDatas(temp / entry.getValue().size());
			sensorList.add(spe);
		}

		if (sensorList.size() == 0)
			return;

		SensorOfAwsPostdataEntity sensorOfAwsPostdataEntity = new SensorOfAwsPostdataEntity();
		sensorOfAwsPostdataEntity.setSensorList(sensorList);
		sensorOfAwsPostdataEntity.setRackConverCode(deviceCode);
		msg.setAwsPostdata(sensorOfAwsPostdataEntity);
		msg.setDevType(DEV_TYPE);
		msg.setTimestamp(System.currentTimeMillis());
		String json = JSON.toJSONString(msg);
		activeMqClient.send(SEND_TOPIC, json);
		logger.info("发送温度:" + json);

		temperatureList.clear();
		sensorList.clear();
		sensorOfAwsPostdataEntity.setSensorList(null);
		sensorOfAwsPostdataEntity = null;
		msg.setAwsPostdata(null);
		msg = null;
	}
}
